package com.example.demo.test;

import com.example.demo.*;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.*;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class LockManager {

    private final ReentrantLock reentrantLock;

    public final static Map<Lock, LockData> LOCKS = new ConcurrentHashMap<>();

    public LockManager(ReentrantLock reentrantLock) {
        this.reentrantLock = reentrantLock;
    }


    public <T> LockTaskResult<T> lock(Long timeOut, LockTask<T> lockTask, LockTaskCallback lockTaskCallback) {
        try {
            if (reentrantLock.tryLock(timeOut, TimeUnit.SECONDS))
                return lockTask.apply(reentrantLock, System.currentTimeMillis(), timeOut, lockTaskCallback);
            return LockTaskResult.lockFail();
        } catch (Exception e) {
            return LockTaskResult.lockFail();
        }
    }

    public static void main(String[] args) throws InterruptedException {

        ExecutorService executorService = Executors.newFixedThreadPool(2);
        ExecutorService singleThreadExecutor = Executors.newSingleThreadExecutor();
        List<Callable<String>> runnableList = new ArrayList<>();
        DefaultTaskCallback taskCallback = new DefaultTaskCallback();

        singleThreadExecutor.execute(taskCallback);

        for (int i = 0; i < 10; i++) {
            runnableList.add(() -> {
                long l = System.currentTimeMillis();
                ReentrantLock reentrantLock = new ReentrantLock();
                taskCallback.addLock(reentrantLock);
                LockManager lockManager = new LockManager(reentrantLock);
                LockTaskResult<Integer> lock = lockManager.lock(1L, new TestLockTask(), taskCallback);
                return lock + "----" + (System.currentTimeMillis() - l);
            });
        }

        List<Future<String>> futures = executorService.invokeAll(runnableList);
        futures.forEach(a -> {
            try {
                System.err.println(a.get());
            } catch (InterruptedException | ExecutionException e) {
                e.printStackTrace();
            }
        });

    }
}
